<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试管理 - 管理员端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin: 0;
        }

        .filters-bar {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .filters-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-label {
            font-size: 12px;
            color: #666;
            font-weight: 500;
        }

        .exams-table-container {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .table-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th {
            background: var(--neutral-light);
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: var(--neutral-dark);
            border-bottom: 1px solid var(--border-color);
        }

        .table td {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }

        .exam-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .exam-icon {
            font-size: 24px;
            width: 40px;
            height: 40px;
            background: var(--primary-light);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .exam-details h4 {
            margin: 0 0 4px 0;
            font-size: 16px;
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .exam-details p {
            margin: 0;
            font-size: 14px;
            color: #666;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-draft {
            background: #fff3cd;
            color: #856404;
        }

        .status-published {
            background: #d4edda;
            color: #155724;
        }

        .status-stopped {
            background: #fff3cd;
            color: #856404;
        }

        .status-ended {
            background: #f8d7da;
            color: #721c24;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        .btn-view {
            background: #e3f2fd;
            color: #1976d2;
        }

        .btn-edit {
            background: #fff3e0;
            color: #f57c00;
        }

        .btn-publish {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .btn-stop {
            background: #fff3e0;
            color: #f57c00;
        }

        .btn-delete {
            background: #ffebee;
            color: #d32f2f;
        }

        .btn-config {
            background: #e3f2fd;
            color: #1976d2;
        }

        .btn-icon:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .pagination-container {
            padding: 20px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: center;
        }

        .pagination {
            display: flex;
            gap: 8px;
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .pagination li {
            display: inline-block;
        }

        .pagination a {
            display: block;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: var(--neutral-dark);
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .pagination a:hover {
            background: var(--primary-light);
            border-color: var(--primary);
        }

        .pagination .active a {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            color: #ccc;
        }

        .empty-state p {
            margin: 0;
            font-size: 16px;
        }

        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .loading-spinner {
            width: 32px;
            height: 32px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 700px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0;
        }

        .btn-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--neutral-dark);
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .modal-footer {
            padding: 20px 24px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .btn-modal {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .btn-cancel {
            background: var(--neutral-light);
            color: var(--neutral-dark);
        }

        .btn-save {
            background: var(--primary);
            color: #000000;
            font-weight: 600;
        }

        .btn-save:hover {
            background: #4a5bb8;
            color: #000000;
        }

        .btn-modal:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        /* 表单行布局 */
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group-half {
            flex: 1;
        }

        /* 表单提示样式 */
        .form-hint {
            margin-top: 8px;
            padding: 8px 12px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            font-size: 13px;
            color: #6c757d;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.3s ease;
        }

        .form-hint i {
            font-size: 14px;
        }

        /* 表单标签图标 */
        .form-label i {
            margin-right: 8px;
            font-size: 16px;
        }

        /* 考试预览区域 */
        .exam-preview {
            margin-top: 20px;
            padding: 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
        }

        .preview-header {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .preview-header i {
            font-size: 18px;
        }

        .preview-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
        }

        .preview-item {
            display: flex;
            align-items: center;
            font-size: 14px;
        }

        .preview-label {
            font-weight: 500;
            margin-right: 8px;
            opacity: 0.9;
        }

        .preview-value {
            font-weight: 600;
            color: #fff;
        }

        /* 题型标签样式 */
        .question-type-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 8px;
            margin-bottom: 4px;
        }

        .question-type-badge.type-1 {
            background: #e3f2fd;
            color: #1976d2;
            border: 1px solid #2196f3;
        }

        .question-type-badge.type-2 {
            background: #f3e5f5;
            color: #7b1fa2;
            border: 1px solid #9c27b0;
        }

        .question-type-badge.type-3 {
            background: #e8f5e8;
            color: #388e3c;
            border: 1px solid #4caf50;
        }

        /* 题目标题样式 */
        .question-title {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            margin-bottom: 8px;
            line-height: 1.4;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 0;
            }
            
            .preview-content {
                grid-template-columns: 1fr;
            }
            
            .modal-content {
                max-width: 95%;
                margin: 2% auto;
            }
        }

        /* 考试详情模态框样式 */
        .exam-detail-content {
            max-height: 70vh;
            overflow-y: auto;
        }

        .exam-basic-info,
        .exam-questions-section,
        .exam-students-section {
            margin-bottom: 30px;
        }

        .exam-basic-info h4,
        .exam-questions-section h4,
        .exam-students-section h4 {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-light);
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 15px;
        }

        .info-item {
            display: flex;
            align-items: center;
            padding: 12px;
            background: var(--neutral-light);
            border-radius: 8px;
        }

        .info-item label {
            font-weight: 600;
            color: var(--neutral-dark);
            margin-right: 10px;
            min-width: 80px;
        }

        .info-item span {
            color: #666;
            flex: 1;
        }

        .questions-list,
        .students-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 15px;
        }

        .question-item,
        .student-item {
            padding: 12px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .question-item:last-child,
        .student-item:last-child {
            border-bottom: none;
        }

        .question-content {
            flex: 1;
        }

        .question-title {
            font-weight: 600;
            color: var(--neutral-dark);
            margin-bottom: 5px;
        }

        .question-meta {
            font-size: 12px;
            color: #666;
        }

        .question-type {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .type-single {
            background: #e3f2fd;
            color: #1976d2;
        }

        .type-multiple {
            background: #fff3e0;
            color: #f57c00;
        }

        .type-judge {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .student-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .student-avatar {
            width: 32px;
            height: 32px;
            background: var(--primary-light);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: var(--primary);
        }

        .student-details h5 {
            margin: 0;
            font-size: 14px;
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .student-details p {
            margin: 0;
            font-size: 12px;
            color: #666;
        }

        .student-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-not-started {
            background: #f8d7da;
            color: #721c24;
        }

        /* 考试配置模态框样式 */
        .exam-config-content {
            max-height: 70vh;
            overflow-y: auto;
        }

        .config-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: #fafafa;
        }

        .config-section h4 {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-light);
        }

        .question-management,
        .student-management {
            margin-top: 15px;
        }

        .question-actions,
        .student-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 10px;
            background: white;
            border-radius: 6px;
            border: 1px solid var(--border-color);
        }

        .question-list,
        .student-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: white;
        }

        .question-item,
        .student-item {
            padding: 12px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .question-item:last-child,
        .student-item:last-child {
            border-bottom: none;
        }

        .question-content,
        .student-content {
            flex: 1;
        }

        .question-title,
        .student-name {
            font-weight: 600;
            color: var(--neutral-dark);
            margin-bottom: 4px;
        }

        .question-meta,
        .student-meta {
            font-size: 12px;
            color: #666;
        }

        .remove-btn {
            background: #ffebee;
            color: #d32f2f;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .remove-btn:hover {
            background: #ffcdd2;
        }

        /* 添加题目/学生模态框样式 */
        .available-questions-list,
        .available-students-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: white;
        }

        .available-question-item,
        .available-student-item {
            padding: 12px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .available-question-item:last-child,
        .available-student-item:last-child {
            border-bottom: none;
        }

        .add-btn {
            background: #e8f5e8;
            color: #2e7d32;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .add-btn:hover {
            background: #c8e6c9;
        }

        .add-btn:disabled {
            background: #f5f5f5;
            color: #999;
            cursor: not-allowed;
        }

        /* 题目信息显示样式 */
        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .question-number {
            background: #e3f2fd;
            color: #1976d2;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .question-difficulty {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .difficulty-1 {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .difficulty-2 {
            background: #fff3e0;
            color: #f57c00;
        }

        .difficulty-3 {
            background: #ffebee;
            color: #d32f2f;
        }

        .meta-item {
            display: inline-block;
            margin-right: 15px;
            font-size: 12px;
            color: #666;
        }

        .meta-item:last-child {
            margin-right: 0;
        }

        .question-title {
            font-weight: 600;
            color: var(--neutral-dark);
            margin-bottom: 8px;
            line-height: 1.4;
        }

        .question-meta {
            font-size: 12px;
            color: #666;
            line-height: 1.3;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>管理员工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="users.html" class="nav-link">
                    <i>👥</i> 用户管理
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="pending-videos.html" class="nav-link">
                    <i>📹</i> 待审核视频
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link active">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <div class="page-header">
                <h1 class="page-title">考试管理</h1>
                <div class="page-actions">
                    <button class="btn btn-primary" onclick="showCreateExamModal()">
                        <i>➕</i> 创建新考试
                    </button>
                </div>
            </div>

            <div class="filters-bar">
                <div class="filters-row">
                    <div class="filter-group">
                        <label class="filter-label">搜索</label>
                        <input type="text" class="form-control" placeholder="搜索考试..." id="searchInput">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">状态</label>
                        <select class="form-control" id="statusFilter">
                            <option value="">全部状态</option>
                            <option value="0">草稿</option>
                            <option value="1">已发布</option>
                            <option value="2">已结束</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <button class="btn btn-secondary" onclick="searchExams()">🔍 搜索</button>
                    </div>
                </div>
            </div>

            <div class="exams-table-container">
                <div class="table-header">
                    <h3 class="table-title">考试列表</h3>
                    <div class="table-actions">
                        <span class="text-muted">共 <span id="totalExams">0</span> 个考试</span>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>考试信息</th>
                                <th>状态</th>
                                <th>题目数量</th>
                                <th>时间限制</th>
                                <th>创建者</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="examList">
                            <tr>
                                <td colspan="7" class="text-center">
                                    <div class="loading">加载中...</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="pagination-container">
                    <ul class="pagination" id="pagination">
                        <!-- 分页按钮将在这里生成 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>

    <!-- 考试详情模态框 -->
    <div class="modal" id="examDetailModal">
        <div class="modal-content" style="max-width: 1000px;">
            <div class="modal-header">
                <h3 class="modal-title" id="examDetailTitle">考试详情</h3>
                <button class="btn-close" onclick="hideExamDetailModal()">&times;</button>
            </div>
            <div class="modal-body" style="padding: 24px;">
                <div class="exam-detail-content">
                    <div class="exam-basic-info">
                        <h4>基本信息</h4>
                        <div class="info-grid">
                            <div class="info-item">
                                <label>考试标题：</label>
                                <span id="detailTitle">-</span>
                            </div>
                            <div class="info-item">
                                <label>考试描述：</label>
                                <span id="detailDescription">-</span>
                            </div>
                            <div class="info-item">
                                <label>题目数量：</label>
                                <span id="detailTotalQuestions">-</span>
                            </div>
                            <div class="info-item">
                                <label>考试时长：</label>
                                <span id="detailTimeLimit">-</span>
                            </div>
                            <div class="info-item">
                                <label>考试状态：</label>
                                <span id="detailStatus">-</span>
                            </div>
                            <div class="info-item">
                                <label>创建时间：</label>
                                <span id="detailCreateTime">-</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="exam-questions-section">
                        <h4>考试题目</h4>
                        <div id="examQuestionsList" class="questions-list">
                            <div class="loading">加载中...</div>
                        </div>
                    </div>
                    
                    <div class="exam-students-section">
                        <h4>参与学生</h4>
                        <div id="examStudentsList" class="students-list">
                            <div class="loading">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideExamDetailModal()">关闭</button>
                <button class="btn-modal btn-save" onclick="editCurrentExam()">编辑考试</button>
            </div>
        </div>
    </div>

    <!-- 考试配置模态框 -->
    <div class="modal" id="examConfigModal">
        <div class="modal-content" style="max-width: 1200px;">
            <div class="modal-header">
                <h3 class="modal-title" id="examConfigTitle">考试配置</h3>
                <button class="btn-close" onclick="hideExamConfigModal()">&times;</button>
            </div>
            <div class="modal-body" style="padding: 24px;">
                <div class="exam-config-content">
                    <!-- 考试基本信息 -->
                    <div class="config-section">
                        <h4>考试信息</h4>
                        <div class="exam-basic-info">
                            <div class="info-item">
                                <label>考试标题：</label>
                                <span id="configExamTitle">-</span>
                            </div>
                            <div class="info-item">
                                <label>题目库总数：</label>
                                <span id="configTotalQuestions">-</span>
                            </div>
                            <div class="info-item">
                                <label>应考题目数：</label>
                                <input type="number" id="configExamQuestions" min="1" max="100" class="form-control" style="width: 100px; display: inline-block;">
                            </div>
                            <div class="info-item">
                                <label>考试时长：</label>
                                <span id="configTimeLimit">-</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 题目管理 -->
                    <div class="config-section">
                        <h4>题目管理</h4>
                        <div class="question-management">
                            <div class="question-actions">
                                <button class="btn btn-primary" onclick="showAddQuestionModal()">
                                    <i>➕</i> 添加题目
            </button>
                                <span class="text-muted">已添加 <span id="addedQuestionCount">0</span> 个题目</span>
                            </div>
                            <div class="question-list" id="examQuestionList">
                                <div class="loading">加载中...</div>
                            </div>
            </div>
        </div>

                    <!-- 学生管理 -->
                    <div class="config-section">
                        <h4>学生管理</h4>
                        <div class="student-management">
                            <div class="student-actions">
                                <button class="btn btn-primary" onclick="showAddStudentModal()">
                                    <i>➕</i> 添加学生
                                </button>
                                <span class="text-muted">已添加 <span id="addedStudentCount">0</span> 个学生</span>
                            </div>
                            <div class="student-list" id="examStudentList">
                                <div class="loading">加载中...</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideExamConfigModal()">关闭</button>
                <button class="btn-modal btn-save" onclick="saveExamConfig()">保存配置</button>
            </div>
        </div>
        </div>

    <!-- 添加题目模态框 -->
    <div class="modal" id="addQuestionModal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 class="modal-title">添加题目到考试</h3>
                <button class="btn-close" onclick="hideAddQuestionModal()">&times;</button>
            </div>
            <div class="modal-body" style="padding: 24px;">
                <div class="question-selection">
                    <div class="filters-bar">
                        <div class="filters-row">
                            <div class="filter-group">
                                <label class="filter-label">搜索题目</label>
                                <input type="text" class="form-control" placeholder="搜索题目内容..." id="questionSearchInput">
                            </div>
                            <div class="filter-group">
                                <label class="filter-label">题型</label>
                                <select class="form-control" id="questionTypeFilter">
                                    <option value="">全部题型</option>
                                    <option value="1">单选题</option>
                                    <option value="2">多选题</option>
                                    <option value="3">判断题</option>
                                </select>
                            </div>
                            <div class="filter-group">
                                <button class="btn btn-secondary" onclick="searchAvailableQuestions()">🔍 搜索</button>
                            </div>
                        </div>
                    </div>
                    <div class="available-questions-list" id="availableQuestionsList">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideAddQuestionModal()">取消</button>
            </div>
        </div>
        </div>

    <!-- 添加学生模态框 -->
    <div class="modal" id="addStudentModal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 class="modal-title">添加学生到考试</h3>
                <button class="btn-close" onclick="hideAddStudentModal()">&times;</button>
            </div>
            <div class="modal-body" style="padding: 24px;">
                <div class="student-selection">
                    <div class="filters-bar">
                        <div class="filters-row">
                            <div class="filter-group">
                                <label class="filter-label">搜索学生</label>
                                <input type="text" class="form-control" placeholder="搜索学生姓名或学号..." id="studentSearchInput">
                            </div>
                            <div class="filter-group">
                                <button class="btn btn-secondary" onclick="searchAvailableStudents()">🔍 搜索</button>
                            </div>
                        </div>
                    </div>
                    <div class="available-students-list" id="availableStudentsList">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideAddStudentModal()">取消</button>
            </div>
        </div>
    </div>

    <!-- 创建/编辑考试模态框 -->
    <div class="modal" id="examModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modalTitle">
                    <i>📝</i> 创建新考试
                </h3>
                <button class="btn-close" onclick="hideExamModal()">&times;</button>
            </div>
            <form id="examForm">
                <div class="form-group">
                    <label class="form-label" for="examTitle">
                        <i>📋</i> 考试标题
                    </label>
                    <input type="text" class="form-control" id="examTitle" name="title" placeholder="请输入考试标题..." required>
                    <div class="form-hint">
                        <i>💡</i> 建议使用简洁明了的标题，如"Java基础测试"、"期中考试"等
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="examDescription">
                        <i>📄</i> 考试描述
                    </label>
                    <textarea class="form-control form-textarea" id="examDescription" name="description" placeholder="请输入考试描述，如考试范围、注意事项等..." rows="3"></textarea>
                    <div class="form-hint">
                        <i>💡</i> 可以描述考试内容、范围、注意事项等，帮助学生了解考试要求
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group form-group-half">
                        <label class="form-label" for="totalQuestions">
                            <i>🔢</i> 题目数量
                        </label>
                        <input type="number" class="form-control" id="totalQuestions" name="totalQuestions" min="1" max="50" placeholder="10" required>
                        <div class="form-hint">
                            <i>💡</i> 建议5-20题，确保考试时间合理
                        </div>
                    </div>
                    
                    <div class="form-group form-group-half">
                        <label class="form-label" for="timeLimit">
                            <i>⏱️</i> 考试时长（分钟）
                        </label>
                        <input type="number" class="form-control" id="timeLimit" name="timeLimit" min="5" max="180" value="60" placeholder="60" required>
                        <div class="form-hint">
                            <i>💡</i> 建议每题2-5分钟，根据题目难度调整
                        </div>
                    </div>
                </div>
                
                <div class="exam-preview" id="examPreview">
                    <div class="preview-header">
                        <i>👁️</i> 考试预览
                    </div>
                    <div class="preview-content">
                        <div class="preview-item">
                            <span class="preview-label">考试标题：</span>
                            <span class="preview-value" id="previewTitle">未设置</span>
                        </div>
                        <div class="preview-item">
                            <span class="preview-label">题目数量：</span>
                            <span class="preview-value" id="previewQuestions">0 题</span>
                        </div>
                        <div class="preview-item">
                            <span class="preview-label">考试时长：</span>
                            <span class="preview-value" id="previewTime">0 分钟</span>
                        </div>
                        <div class="preview-item">
                            <span class="preview-label">预计每题用时：</span>
                            <span class="preview-value" id="previewTimePerQuestion">-</span>
                        </div>
                    </div>
                </div>
            </form>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideExamModal()">
                    <i>❌</i> 取消
                </button>
                <button class="btn-modal btn-save" onclick="saveExam()">
                    <i>💾</i> 保存
                </button>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let exams = [];
        let currentExamId = null;
        let isEditMode = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExams();
            
            // 检查URL参数，如果有config参数则自动打开配置模态框
            const urlParams = new URLSearchParams(window.location.search);
            const configExamId = urlParams.get('config');
            if (configExamId) {
                setTimeout(() => {
                    configExam(parseInt(configExamId));
                }, 1000); // 延迟1秒确保页面完全加载
            }
        });

        // 检查用户权限
        async function checkAuth() {
            const user = await UserManager.init();
            if (!user || user.role !== 0) {
                Message.error('请先登录管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
        }

        // 加载考试列表
        async function loadExams() {
            try {
                const response = await API.get('/exam/admin/all');
                if (response.success) {
                    exams = response.exams || [];
                    renderExamList();
                } else {
                    Message.error(response.message || '加载考试列表失败');
                    showEmptyState();
                }
            } catch (error) {
                console.error('加载考试列表失败:', error);
                Message.error('加载考试列表失败，请稍后重试');
                showEmptyState();
            }
        }

        // 渲染考试列表
        function renderExamList() {
            const examList = document.getElementById('examList');

            if (exams.length === 0) {
                showEmptyState();
                return;
            }
            
            examList.innerHTML = exams.map(exam => {
                const statusClass = getStatusClass(exam.status);
                const statusText = getStatusText(exam.status);

                return `
                    <tr>
                        <td>
                            <div class="exam-info">
                                <div class="exam-icon">📝</div>
                                <div class="exam-details">
                                    <h4>${exam.title}</h4>
                                    <p>${exam.description || '暂无描述'}</p>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </td>
                        <td>${exam.totalQuestions || 0} 题</td>
                        <td>${exam.timeLimit || 0} 分钟</td>
                        <td>${exam.teacherName || '未知'}</td>
                        <td>${formatDate(exam.createdTime)}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn-icon btn-config" onclick="configExam(${exam.id})" title="配置考试">
                                    ⚙️
                                </button>
                                <button class="btn-icon btn-view" onclick="viewExamResults(${exam.id})" title="查看结果">
                                    📊
                                </button>
                            ${exam.status === 0 ? 
                                    `<button class="btn-icon btn-publish" onclick="publishExam(${exam.id})" title="发布">📢</button>` : 
                                ''
                            }
                                ${exam.status === 1 ? 
                                    `<button class="btn-icon btn-stop" onclick="stopExam(${exam.id})" title="停止考试">⏹️</button>` : 
                                    ''
                                }
                                <button class="btn-icon btn-delete" onclick="deleteExam(${exam.id})" title="删除">
                                    🗑️
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            }).join('');
            
            document.getElementById('totalExams').textContent = exams.length;
        }

        // 显示空状态
        function showEmptyState() {
            const examList = document.getElementById('examList');
            examList.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center">
                        <div class="empty-state">
                            <i>📝</i>
                            <p>暂无考试数据</p>
                        </div>
                    </td>
                </tr>
            `;
            document.getElementById('totalExams').textContent = '0';
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case 0: return 'status-draft';
                case 1: return 'status-published';
                case 2: return 'status-stopped';
                case 3: return 'status-ended';
                default: return 'status-draft';
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 0: return '草稿';
                case 1: return '已发布';
                case 2: return '已停止';
                case 3: return '已结束';
                default: return '未知';
            }
        }

        // 格式化日期
        function formatDate(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }

        // 显示创建考试模态框
        function showCreateExamModal() {
            isEditMode = false;
            currentExamId = null;
            document.getElementById('modalTitle').innerHTML = '<i>📝</i> 创建新考试';
            document.getElementById('examForm').reset();
            document.getElementById('examModal').style.display = 'flex';
            updateExamPreview(); // 初始化预览
            setupExamFormListeners(); // 设置表单监听器
        }

        // 设置表单监听器
        function setupExamFormListeners() {
            const examTitle = document.getElementById('examTitle');
            const totalQuestions = document.getElementById('totalQuestions');
            const timeLimit = document.getElementById('timeLimit');

            examTitle.addEventListener('input', updateExamPreview);
            totalQuestions.addEventListener('input', updateExamPreview);
            timeLimit.addEventListener('input', updateExamPreview);
        }

        // 更新考试预览
        function updateExamPreview() {
            const title = document.getElementById('examTitle').value || '未设置';
            const questions = parseInt(document.getElementById('totalQuestions').value) || 0;
            const time = parseInt(document.getElementById('timeLimit').value) || 0;
            
            document.getElementById('previewTitle').textContent = title;
            document.getElementById('previewQuestions').textContent = questions + ' 题';
            document.getElementById('previewTime').textContent = time + ' 分钟';
            
            // 计算每题用时
            if (questions > 0 && time > 0) {
                const timePerQuestion = (time / questions).toFixed(1);
                document.getElementById('previewTimePerQuestion').textContent = timePerQuestion + ' 分钟/题';
            } else {
                document.getElementById('previewTimePerQuestion').textContent = '-';
            }
        }

        // 编辑考试
        function editExam(examId) {
            const exam = exams.find(e => e.id === examId);
            if (!exam) {
                Message.error('考试不存在');
                return;
            }
            
            isEditMode = true;
            currentExamId = examId;
            document.getElementById('modalTitle').innerHTML = '<i>✏️</i> 编辑考试';
            document.getElementById('examTitle').value = exam.title;
            document.getElementById('examDescription').value = exam.description || '';
            document.getElementById('totalQuestions').value = exam.totalQuestions || 0;
            document.getElementById('timeLimit').value = exam.timeLimit || 60;
            document.getElementById('examModal').style.display = 'flex';
            updateExamPreview(); // 更新预览
            setupExamFormListeners(); // 设置表单监听器
        }

        // 隐藏模态框
        function hideExamModal() {
            document.getElementById('examModal').style.display = 'none';
        }

        // 保存考试
        async function saveExam() {
            const form = document.getElementById('examForm');
            const formData = new FormData(form);
            const examData = {
                title: formData.get('title'),
                description: formData.get('description'),
                totalQuestions: parseInt(formData.get('totalQuestions')),
                timeLimit: parseInt(formData.get('timeLimit'))
            };

            try {
                let response;
                if (isEditMode) {
                    examData.id = currentExamId;
                    response = await API.put('/exam/update/' + currentExamId, examData);
                } else {
                    response = await API.post('/exam/create', examData);
                }

                if (response.success) {
                    Message.success(response.message);
                    hideExamModal();
                    loadExams();
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('保存考试失败:', error);
                Message.error('保存考试失败，请稍后重试');
            }
        }

        // 查看考试详情
        function viewExamDetail(examId) {
            // 跳转到考试详情页面
            window.location.href = `exam-details.html?examId=${examId}`;
        }

        // 配置考试
        function configExam(examId) {
            // 显示考试配置模态框
            showExamConfigModal(examId);
        }


        // 显示考试详情模态框
        async function showExamDetailModal(examId) {
            try {
                // 显示模态框
                document.getElementById('examDetailModal').style.display = 'flex';
                
                // 加载考试基本信息
                const examResponse = await API.get(`/exam/${examId}`);
                if (examResponse.success) {
                    const exam = examResponse.exam;
                    document.getElementById('detailTitle').textContent = exam.title;
                    document.getElementById('detailDescription').textContent = exam.description || '暂无描述';
                    document.getElementById('detailTotalQuestions').textContent = exam.totalQuestions || 0;
                    document.getElementById('detailTimeLimit').textContent = exam.timeLimit || 0;
                    document.getElementById('detailStatus').textContent = getStatusText(exam.status);
                    document.getElementById('detailCreateTime').textContent = formatDate(exam.createdTime);
                    document.getElementById('examDetailTitle').textContent = exam.title;
                    
                    // 保存当前考试ID用于编辑
                    currentExamId = examId;
                } else {
                    Message.error('加载考试信息失败');
                    return;
                }
                
                // 加载考试题目
                const questionsResponse = await API.get(`/exam/${examId}/questions`);
                if (questionsResponse.success) {
                    const questions = questionsResponse.questions || [];
                    renderExamQuestions(questions);
                } else {
                    document.getElementById('examQuestionsList').innerHTML = '<div class="empty-state"><p>加载题目失败</p></div>';
                }
                
                // 加载参与学生
                const studentsResponse = await API.get(`/exam/${examId}/students`);
                if (studentsResponse.success) {
                    const students = studentsResponse.students || [];
                    renderExamStudents(students);
                } else {
                    document.getElementById('examStudentsList').innerHTML = '<div class="empty-state"><p>加载学生信息失败</p></div>';
                }
                
            } catch (error) {
                console.error('加载考试详情失败:', error);
                Message.error('加载考试详情失败，请稍后重试');
            }
        }

        // 隐藏考试详情模态框
        function hideExamDetailModal() {
            document.getElementById('examDetailModal').style.display = 'none';
        }

        // 渲染考试题目
        function renderExamQuestions(questions) {
            const questionsList = document.getElementById('examQuestionsList');
            
            if (questions.length === 0) {
                questionsList.innerHTML = '<div class="empty-state"><p>暂无题目</p></div>';
                return;
            }
            
            questionsList.innerHTML = questions.map(question => {
                const typeClass = getQuestionTypeClass(question.type);
                const typeText = getQuestionTypeText(question.type);
                
                return `
                    <div class="question-item">
                        <div class="question-content">
                            <div class="question-title">${question.title}</div>
                            <div class="question-meta">
                                难度: ${getDifficultyText(question.difficulty)} | 
                                正确答案: ${question.answer}
                            </div>
                        </div>
                        <span class="question-type ${typeClass}">${typeText}</span>
                    </div>
                `;
            }).join('');
        }

        // 渲染参与学生
        function renderExamStudents(students) {
            const studentsList = document.getElementById('examStudentsList');
            
            if (students.length === 0) {
                studentsList.innerHTML = '<div class="empty-state"><p>暂无学生参与</p></div>';
                return;
            }
            
            studentsList.innerHTML = students.map(student => {
                const statusClass = getStudentStatusClass(student.status);
                const statusText = getStudentStatusText(student.status);
                
                return `
                    <div class="student-item">
                        <div class="student-info">
                            <div class="student-avatar">${student.name.charAt(0)}</div>
                            <div class="student-details">
                                <h5>${student.name}</h5>
                                <p>学号: ${student.username}</p>
                            </div>
                        </div>
                        <span class="student-status ${statusClass}">${statusText}</span>
                    </div>
                `;
            }).join('');
        }

        // 获取题目类型样式类
        function getQuestionTypeClass(type) {
            switch (type) {
                case 1: return 'type-single';
                case 2: return 'type-multiple';
                case 3: return 'type-judge';
                default: return 'type-single';
            }
        }

        // 获取题目类型文本
        function getQuestionTypeText(type) {
            switch (type) {
                case 1: return '单选题';
                case 2: return '多选题';
                case 3: return '判断题';
                default: return '未知';
            }
        }

        // 获取难度文本
        function getDifficultyText(difficulty) {
            switch (difficulty) {
                case 1: return '简单';
                case 2: return '中等';
                case 3: return '困难';
                default: return '未知';
            }
        }

        // 获取学生状态样式类
        function getStudentStatusClass(status) {
            switch (status) {
                case 1: return 'status-completed';
                case 0: return 'status-pending';
                default: return 'status-not-started';
            }
        }

        // 获取学生状态文本
        function getStudentStatusText(status) {
            switch (status) {
                case 1: return '已完成';
                case 0: return '进行中';
                default: return '未开始';
            }
        }

        // 编辑当前考试
        function editCurrentExam() {
            if (currentExamId) {
                hideExamDetailModal();
                editExam(currentExamId);
            }
        }

        // 查看考试结果
        function viewExamResults(examId) {
            window.location.href = `exam-results.html?examId=${examId}`;
        }

        // 发布考试
        async function publishExam(examId) {
            if (!confirm('确定要发布这个考试吗？')) return;

            try {
                const response = await API.put(`/exam/admin/publish/${examId}`);
                if (response.success) {
                    Message.success('考试发布成功');
                    loadExams();
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('发布考试失败:', error);
                Message.error('发布考试失败，请稍后重试');
            }
        }

        // 停止考试
        async function stopExam(examId) {
            if (!confirm('确定要停止这个考试吗？停止后学生将无法继续答题。')) return;

            try {
                const response = await API.put(`/exam/admin/stop/${examId}`, {});
                if (response.success) {
                    Message.success('考试已停止');
                    loadExams();
                } else {
                    Message.error(response.message || '停止考试失败');
                }
            } catch (error) {
                console.error('停止考试失败:', error);
                Message.error('停止考试失败，请稍后重试');
            }
        }

        // 删除考试
        async function deleteExam(examId) {
            if (!confirm('确定要删除这个考试吗？此操作不可恢复！')) return;

            try {
                const response = await API.delete(`/exam/admin/delete/${examId}`);
                if (response.success) {
                    Message.success('考试删除成功');
                    loadExams();
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('删除考试失败:', error);
                Message.error('删除考试失败，请稍后重试');
            }
        }

        // 搜索考试
        function searchExams() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;
            
            let filteredExams = exams.filter(exam => {
                const matchesSearch = exam.title.toLowerCase().includes(searchTerm) || 
                                    (exam.description && exam.description.toLowerCase().includes(searchTerm));
                const matchesStatus = !statusFilter || exam.status.toString() === statusFilter;
                return matchesSearch && matchesStatus;
            });

            // 临时更新显示
            const examList = document.getElementById('examList');
            if (filteredExams.length === 0) {
                examList.innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center">
                            <div class="empty-state">
                                <i>🔍</i>
                                <p>没有找到匹配的考试</p>
                            </div>
                        </td>
                    </tr>
                `;
            } else {
                examList.innerHTML = filteredExams.map(exam => {
                    const statusClass = getStatusClass(exam.status);
                    const statusText = getStatusText(exam.status);

                    return `
                        <tr>
                            <td>
                                <div class="exam-info">
                                    <div class="exam-icon">📝</div>
                                    <div class="exam-details">
                                        <h4>${exam.title}</h4>
                                        <p>${exam.description || '暂无描述'}</p>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge ${statusClass}">${statusText}</span>
                            </td>
                            <td>${exam.totalQuestions || 0} 题</td>
                            <td>${exam.timeLimit || 0} 分钟</td>
                            <td>${exam.teacherName || '未知'}</td>
                            <td>${formatDate(exam.createdTime)}</td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-icon btn-config" onclick="configExam(${exam.id})" title="配置考试">
                                        ⚙️
                                    </button>
                                    <button class="btn-icon btn-view" onclick="viewExamResults(${exam.id})" title="查看结果">
                                        📊
                                    </button>
                                    ${exam.status === 0 ? 
                                        `<button class="btn-icon btn-publish" onclick="publishExam(${exam.id})" title="发布">📢</button>` : 
                                        ''
                                    }
                                    ${exam.status === 1 ? 
                                        `<button class="btn-icon btn-stop" onclick="stopExam(${exam.id})" title="停止考试">⏹️</button>` : 
                                        ''
                                    }
                                    <button class="btn-icon btn-delete" onclick="deleteExam(${exam.id})" title="删除">
                                        🗑️
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                }).join('');
            }

            document.getElementById('totalExams').textContent = filteredExams.length;
        }

        // 考试配置相关变量
        let currentConfigExamId = null;
        let examQuestions = [];
        let examStudents = [];
        let availableQuestions = [];
        let availableStudents = [];

        // 显示考试配置模态框
        async function showExamConfigModal(examId) {
            try {
                currentConfigExamId = examId;
                document.getElementById('examConfigModal').style.display = 'flex';
                
                // 加载考试基本信息
                const examResponse = await API.get(`/exam/${examId}`);
                if (examResponse.success) {
                    const exam = examResponse.exam;
                    document.getElementById('configExamTitle').textContent = exam.title;
                    document.getElementById('configTotalQuestions').textContent = examQuestions.length; // 显示实际添加的题目数量
                    document.getElementById('configExamQuestions').value = exam.totalQuestions || 1; // 使用totalQuestions作为应考题目数
                    document.getElementById('configTimeLimit').textContent = exam.timeLimit || 0;
                    document.getElementById('examConfigTitle').textContent = `配置考试：${exam.title}`;
                }
                
                // 加载考试题目
                await loadExamQuestions(examId);
                
                // 加载考试学生
                await loadExamStudents(examId);
                
            } catch (error) {
                console.error('加载考试配置失败:', error);
                Message.error('加载考试配置失败，请稍后重试');
            }
        }

        // 隐藏考试配置模态框
        function hideExamConfigModal() {
            document.getElementById('examConfigModal').style.display = 'none';
            currentConfigExamId = null;
            examQuestions = [];
            examStudents = [];
        }

        // 加载考试题目
        async function loadExamQuestions(examId) {
            try {
                const response = await API.get(`/exam/${examId}/questions`);
                if (response.success) {
                    examQuestions = response.questions || [];
                    renderExamQuestionsList();
                    document.getElementById('addedQuestionCount').textContent = examQuestions.length;
                } else {
                    examQuestions = [];
                    document.getElementById('examQuestionList').innerHTML = '<div class="empty-state"><p>加载题目失败</p></div>';
                }
            } catch (error) {
                console.error('加载考试题目失败:', error);
                examQuestions = [];
                document.getElementById('examQuestionList').innerHTML = '<div class="empty-state"><p>加载题目失败</p></div>';
            }
        }

        // 加载考试学生
        async function loadExamStudents(examId) {
            try {
                const response = await API.get(`/exam/${examId}/students`);
                if (response.success) {
                    examStudents = response.students || [];
                    renderExamStudentsList();
                    document.getElementById('addedStudentCount').textContent = examStudents.length;
                } else {
                    examStudents = [];
                    document.getElementById('examStudentList').innerHTML = '<div class="empty-state"><p>加载学生失败</p></div>';
                }
            } catch (error) {
                console.error('加载考试学生失败:', error);
                examStudents = [];
                document.getElementById('examStudentList').innerHTML = '<div class="empty-state"><p>加载学生失败</p></div>';
            }
        }

        // 渲染考试题目列表
        function renderExamQuestionsList() {
            const questionList = document.getElementById('examQuestionList');
            
            if (examQuestions.length === 0) {
                questionList.innerHTML = '<div class="empty-state"><p>暂无题目</p></div>';
                return;
            }

            questionList.innerHTML = examQuestions.map((examQuestion, index) => {
                // 从examQuestion对象中获取question对象
                const question = examQuestion.question || examQuestion;
                
                const options = [];
                if (question.optionA) options.push(`A. ${question.optionA}`);
                if (question.optionB) options.push(`B. ${question.optionB}`);
                if (question.optionC) options.push(`C. ${question.optionC}`);
                if (question.optionD) options.push(`D. ${question.optionD}`);
                const optionsText = options.length > 0 ? options.join(', ') : '暂无选项';

                return `
                    <div class="question-item">
                        <div class="question-content">
                            <div class="question-header">
                                <span class="question-number">第${index + 1}题</span>
                                <span class="question-difficulty difficulty-${question.difficulty || 1}">${getDifficultyText(question.difficulty)}</span>
            </div>
                            <div class="question-title">${question.content || '无题目内容'}</div>
                            <div class="question-meta">
                                <span class="meta-item">选项：${optionsText}</span>
                                <span class="meta-item">答案：${question.correctAns || '无'}</span>
                            </div>
                            </div>
                        <button class="remove-btn" onclick="removeQuestionFromExam(${question.id})">移除</button>
                            </div>
                `;
            }).join('');
        }

        // 渲染考试学生列表
        function renderExamStudentsList() {
            const studentList = document.getElementById('examStudentList');
            
            if (examStudents.length === 0) {
                studentList.innerHTML = '<div class="empty-state"><p>暂无学生</p></div>';
                return;
            }

            studentList.innerHTML = examStudents.map(student => {
                return `
                    <div class="student-item">
                        <div class="student-content">
                            <div class="student-name">${student.studentName || '未知学生'}</div>
                            <div class="student-meta">状态：${getStudentStatusText(student.status)}</div>
                        </div>
                        <button class="remove-btn" onclick="removeStudentFromExam(${student.studentId})">移除</button>
                    </div>
                `;
            }).join('');
        }

        // 显示添加题目模态框
        async function showAddQuestionModal() {
            document.getElementById('addQuestionModal').style.display = 'flex';
            await loadAvailableQuestions();
        }

        // 隐藏添加题目模态框
        function hideAddQuestionModal() {
            document.getElementById('addQuestionModal').style.display = 'none';
        }

        // 显示添加学生模态框
        async function showAddStudentModal() {
            document.getElementById('addStudentModal').style.display = 'flex';
            await loadAvailableStudents();
        }

        // 隐藏添加学生模态框
        function hideAddStudentModal() {
            document.getElementById('addStudentModal').style.display = 'none';
        }

        // 加载可用题目
        async function loadAvailableQuestions() {
            try {
                const response = await API.get('/question/admin/all');
                if (response.success) {
                    availableQuestions = response.questions || [];
                    renderAvailableQuestions();
                } else {
                    availableQuestions = [];
                    document.getElementById('availableQuestionsList').innerHTML = '<div class="empty-state"><p>加载题目失败</p></div>';
                }
            } catch (error) {
                console.error('加载可用题目失败:', error);
                availableQuestions = [];
                document.getElementById('availableQuestionsList').innerHTML = '<div class="empty-state"><p>加载题目失败</p></div>';
            }
        }

        // 加载可用学生
        async function loadAvailableStudents() {
            try {
                const response = await API.get('/user/students');
                if (response.success) {
                    availableStudents = response.students || [];
                    renderAvailableStudents();
                } else {
                    availableStudents = [];
                    document.getElementById('availableStudentsList').innerHTML = '<div class="empty-state"><p>加载学生失败</p></div>';
                }
            } catch (error) {
                console.error('加载可用学生失败:', error);
                availableStudents = [];
                document.getElementById('availableStudentsList').innerHTML = '<div class="empty-state"><p>加载学生失败</p></div>';
            }
        }

        // 渲染可用题目列表
        function renderAvailableQuestions() {
            const questionList = document.getElementById('availableQuestionsList');
            
            // 过滤掉已经添加的题目
            const filteredQuestions = availableQuestions.filter(q => 
                !examQuestions.some(eq => {
                    const question = eq.question || eq;
                    return question.id === q.id;
                })
            );
            
            if (filteredQuestions.length === 0) {
                questionList.innerHTML = '<div class="empty-state"><p>没有可添加的题目</p></div>';
                return;
            }

            questionList.innerHTML = filteredQuestions.map(question => {
                const options = [];
                if (question.optionA) options.push(`A. ${question.optionA}`);
                if (question.optionB) options.push(`B. ${question.optionB}`);
                if (question.optionC) options.push(`C. ${question.optionC}`);
                if (question.optionD) options.push(`D. ${question.optionD}`);
                const optionsText = options.length > 0 ? options.join(', ') : '暂无选项';

                return `
                    <div class="available-question-item">
                        <div class="question-content">
                            <div class="question-title">${question.content || '无题目内容'}</div>
                            <div class="question-meta">
                                <span class="meta-item">选项：${optionsText}</span>
                                <span class="meta-item">难度：${getDifficultyText(question.difficulty)}</span>
                                <span class="meta-item">答案：${question.correctAns || '无'}</span>
                            </div>
                        </div>
                        <button class="add-btn" onclick="addQuestionToExam(${question.id})">添加</button>
                    </div>
                `;
            }).join('');
        }

        // 渲染可用学生列表
        function renderAvailableStudents() {
            const studentList = document.getElementById('availableStudentsList');
            
            // 过滤掉已经添加的学生
            const filteredStudents = availableStudents.filter(s => 
                !examStudents.some(es => es.studentId === s.id)
            );
            
            if (filteredStudents.length === 0) {
                studentList.innerHTML = '<div class="empty-state"><p>没有可添加的学生</p></div>';
                return;
            }

            studentList.innerHTML = filteredStudents.map(student => {
                return `
                    <div class="available-student-item">
                        <div class="student-content">
                            <div class="student-name">${student.name || '未知学生'}</div>
                            <div class="student-meta">学号：${student.username || '无'}</div>
                        </div>
                        <button class="add-btn" onclick="addStudentToExam(${student.id})">添加</button>
                    </div>
                `;
            }).join('');
        }

        // 添加题目到考试
        async function addQuestionToExam(questionId) {
            try {
                // 检查是否已经添加过
                if (examQuestions.some(eq => {
                    const question = eq.question || eq;
                    return question.id === questionId;
                })) {
                    Message.warning('该题目已经添加到考试中');
                    return;
                }

                const response = await API.post(`/exam/${currentConfigExamId}/add-question/${questionId}`);
                if (response.success) {
                    Message.success('题目添加成功');
                    
                    // 立即从可用题目列表中移除
                    availableQuestions = availableQuestions.filter(q => q.id !== questionId);
                    
                    // 重新加载考试题目列表
                    await loadExamQuestions(currentConfigExamId);
                    
                    // 重新渲染可用题目列表
                    renderAvailableQuestions();
                } else {
                    Message.error(response.message || '添加题目失败');
                }
            } catch (error) {
                console.error('添加题目失败:', error);
                Message.error('添加题目失败，请稍后重试');
            }
        }

        // 从考试中移除题目
        async function removeQuestionFromExam(questionId) {
            if (!confirm('确定要从考试中移除这个题目吗？')) return;
            
            try {
                const response = await API.post(`/exam/${currentConfigExamId}/remove-question/${questionId}`);
                if (response.success) {
                    Message.success('题目移除成功');
                    
                    // 重新加载考试题目列表
                    await loadExamQuestions(currentConfigExamId);
                    
                    // 重新加载可用题目列表，确保移除的题目重新出现
                    await loadAvailableQuestions();
                } else {
                    Message.error(response.message || '移除题目失败');
                }
            } catch (error) {
                console.error('移除题目失败:', error);
                Message.error('移除题目失败，请稍后重试');
            }
        }

        // 添加学生到考试
        async function addStudentToExam(studentId) {
            try {
                const response = await API.post(`/exam/${currentConfigExamId}/add-student/${studentId}`);
                if (response.success) {
                    Message.success('学生添加成功');
                    await loadExamStudents(currentConfigExamId);
                    await loadAvailableStudents(); // 刷新可用学生列表
                } else {
                    Message.error(response.message || '添加学生失败');
                }
            } catch (error) {
                console.error('添加学生失败:', error);
                Message.error('添加学生失败，请稍后重试');
            }
        }

        // 从考试中移除学生
        async function removeStudentFromExam(studentId) {
            if (!confirm('确定要从考试中移除这个学生吗？')) return;
            
            try {
                const response = await API.post(`/exam/${currentConfigExamId}/remove-student/${studentId}`);
                if (response.success) {
                    Message.success('学生移除成功');
                    await loadExamStudents(currentConfigExamId);
                } else {
                    Message.error(response.message || '移除学生失败');
                }
            } catch (error) {
                console.error('移除学生失败:', error);
                Message.error('移除学生失败，请稍后重试');
            }
        }

        // 搜索可用题目
        function searchAvailableQuestions() {
            const searchTerm = document.getElementById('questionSearchInput').value.toLowerCase();
            const typeFilter = document.getElementById('questionTypeFilter').value;
            
            let filteredQuestions = availableQuestions.filter(q => {
                const matchesSearch = (q.content || '').toLowerCase().includes(searchTerm);
                const matchesType = !typeFilter || (q.type || 1).toString() === typeFilter;
                const notAdded = !examQuestions.some(eq => {
                    const question = eq.question || eq;
                    return question.id === q.id;
                });
                return matchesSearch && matchesType && notAdded;
            });
            
            renderFilteredAvailableQuestions(filteredQuestions);
        }

        // 搜索可用学生
        function searchAvailableStudents() {
            const searchTerm = document.getElementById('studentSearchInput').value.toLowerCase();
            
            let filteredStudents = availableStudents.filter(s => {
                const matchesSearch = (s.name || '').toLowerCase().includes(searchTerm) || 
                                    (s.username || '').toLowerCase().includes(searchTerm);
                const notAdded = !examStudents.some(es => es.studentId === s.id);
                return matchesSearch && notAdded;
            });
            
            renderFilteredAvailableStudents(filteredStudents);
        }

        // 渲染过滤后的可用题目
        function renderFilteredAvailableQuestions(filteredQuestions) {
            const questionList = document.getElementById('availableQuestionsList');
            
            if (filteredQuestions.length === 0) {
                questionList.innerHTML = '<div class="empty-state"><p>没有找到匹配的题目</p></div>';
                return;
            }

            questionList.innerHTML = filteredQuestions.map(question => {
                const questionType = question.type || 1;
                const typeText = getTypeText(questionType);
                const typeIcon = getTypeIcon(questionType);
                
                let optionsText = '暂无选项';
                if (questionType === 3) {
                    // 判断题
                    optionsText = '正确 / 错误';
                } else {
                    // 单选题和多选题
                    const options = [];
                    if (question.optionA) options.push(`A. ${question.optionA}`);
                    if (question.optionB) options.push(`B. ${question.optionB}`);
                    if (question.optionC) options.push(`C. ${question.optionC}`);
                    if (question.optionD) options.push(`D. ${question.optionD}`);
                    if (options.length > 0) {
                        optionsText = options.join(', ');
                    }
                }

                return `
                    <div class="available-question-item">
                        <div class="question-content">
                            <div class="question-title">
                                <span class="question-type-badge type-${questionType}">
                                    ${typeIcon} ${typeText}
                                </span>
                                ${question.content || '无题目内容'}
                            </div>
                            <div class="question-meta">
                                <span class="meta-item">选项：${optionsText}</span>
                                <span class="meta-item">答案：${question.correctAns || '无'}</span>
                            </div>
                        </div>
                        <button class="add-btn" onclick="addQuestionToExam(${question.id})">添加</button>
                    </div>
                `;
            }).join('');
        }

        // 获取题型文本
        function getTypeText(type) {
            switch (type) {
                case 1: return '单选题';
                case 2: return '多选题';
                case 3: return '判断题';
                default: return '单选题';
            }
        }

        // 获取题型图标
        function getTypeIcon(type) {
            switch (type) {
                case 1: return '🔘';
                case 2: return '☑️';
                case 3: return '✅';
                default: return '🔘';
            }
        }

        // 渲染过滤后的可用学生
        function renderFilteredAvailableStudents(filteredStudents) {
            const studentList = document.getElementById('availableStudentsList');
            
            if (filteredStudents.length === 0) {
                studentList.innerHTML = '<div class="empty-state"><p>没有找到匹配的学生</p></div>';
                return;
            }

            studentList.innerHTML = filteredStudents.map(student => {
                return `
                    <div class="available-student-item">
                        <div class="student-content">
                            <div class="student-name">${student.name || '未知学生'}</div>
                            <div class="student-meta">学号：${student.username || '无'}</div>
                        </div>
                        <button class="add-btn" onclick="addStudentToExam(${student.id})">添加</button>
                    </div>
                `;
            }).join('');
        }

        // 保存考试配置
        async function saveExamConfig() {
            try {
                const examQuestions = parseInt(document.getElementById('configExamQuestions').value) || 1;
                
                // 更新考试的应考题目数量
                const response = await API.put(`/exam/${currentConfigExamId}/update-exam-questions`, {
                    examQuestions: examQuestions
                });
                
                if (response.success) {
                    Message.success('考试配置已保存');
                    hideExamConfigModal();
                    loadExams(); // 刷新考试列表
                } else {
                    Message.error(response.message || '保存考试配置失败');
                }
            } catch (error) {
                console.error('保存考试配置失败:', error);
                Message.error('保存考试配置失败，请稍后重试');
            }
        }
    </script>
</body>
</html>
